<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <link rel="stylesheet" href="css/login.css">
</head>

<body>
<div class="container">
    <div class="login">
        <h2>登 录</h2>
        <input type="text" name="username" placeholder="用户名" id="username"/>
        <input type="password" name="password" placeholder="密码" id="password"/>
        <button type="submit" id="submit">登录</button>
        <a href="register.html">注册</a>
    </div>

</div>


<!-- 引入 jQuery -->
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<!-- 实现前后端交互的逻辑 -->
<script>
    let submitButton = document.querySelector('#submit');
    submitButton.onclick = function () {
        // 1. 先获取到输入框中的内容
        let username = document.querySelector('#username').value;
        let password = document.querySelector('#password').value;
        if (username === '' || password === '') {
            alert("当前输入的用户名或者密码为空!");
            return;
        }

        // 2. 再发送 ajax 请求进行登录
        $.ajax({
            url: '/login',
            type: 'post',
            data: {
                username: username,
                password: password
            },
            success: function (body) {
                // 3. 处理响应
                // 此处的 body 相当于响应的 user 对象.
                if (body && body.userId > 0) {
                    // 登录成功!
                    // 跳转到客户端主页面 (聊天页面)
                    location.assign('/client.html');
                } else {
                    alert("登录失败! 用户名或密码错误!");
                }
            }
        });
    }

    // 回车事件
    $(document).ready(function () {
        $(".login input").keydown(function (event) {
            if (event.keyCode == 13) {
                let loginButton = document.querySelector('.login button');
                loginButton.click();
            }
        });
    });
</script>
</body>

</html>